package cn.itcast.order.service;

import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;



@Service
@DefaultProperties(defaultFallback="allMethodFallBack")
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand
    public String queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.远程查询user
        //2.1 url地址
//        String url = "http://localhost:8081/user/ "+ order.getUserId();
        String url = "http://userservice/user/ "+ order.getUserId();
        //2.2发起调用
        User user = restTemplate.getForObject(url,User.class);
        // 3.存入order
        order.setUser(user);
        // 4.返回
        return JSON.toJSONString(order);
    }
    //降级方法
    public String queryOrderByIdFallback(Long orderId) {
        return "服务器太忙，请稍后重试........";
    }
    //全局降级
    public String allMethodFallBack(){
        return " 服务器太太太忙，请稍后重试....";
    }
}
